﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Devfw.OpenAuth.Platform;
using System.Configuration;
using WebSite.Core;
using System.Net;
using System.Text.RegularExpressions;


namespace WebSite.ThirdPartyLogin
{
    public partial class TencentCallback : Page
    {
        protected void Page_Load( object sender, EventArgs e )
        {
            string apiKey = ConfigurationManager.AppSettings["TencentApiKey"]; //"57ba1f3e778f46dfa975d9f9563f9070";
            string apiSecret = ConfigurationManager.AppSettings["TencentApiSecret"]; //"a15df444fed534c8907a13107b524557";
            string callbackUrl = ConfigurationManager.AppSettings["TencentCallbackUrl"];// http://127.0.0.1:8001/tencentcallback.aspx

            TencentV2 tencent = new TencentV2( apiKey, apiSecret );
            var result = tencent.getAccessToken( Request.QueryString["code"], callbackUrl );

            // Response.Write( result );
            // return;

            var nvc = HttpUtility.ParseQueryString( result );
            string accessToken = nvc["access_token"];

            WebClient client = new WebClient();
            string result2 = client.DownloadString( string.Format( "https://graph.qq.com/oauth2.0/me?access_token={0}", accessToken ) );
            // callback( {"client_id":"100306968","openid":"A5D6E32DE5A614A52520154F7DD31F97"} );
            var m = Regex.Match( result2, "(openid\"\\:\")(\\w*)[\"]" );
            if (m.Success)
            {

                string username = "qq$$$" + m.Groups[2].Value;

                LoginHelper.SetCurrentUser( username );
            }
            else
            {
                Response.Write( "登录腾讯平台失败" );
            }
        }
    }
}